package main

import (
	"fmt"
	"zinx-learn/ziface"
	"zinx-learn/znet"
)

type PingRouter struct {
	znet.BaseRouter
}

func (r *PingRouter) Handle(request ziface.IRequest) {
	data := request.GetMessage().GetData()
	s := "server callback " + string(data)
	message := znet.NewMessage(request.GetMessageID(), []byte(s))
	err := request.GetConnection().SendMsg(message)
	if err != nil {
		fmt.Println("handle error", err.Error())
	}
}

type HelloRouter struct {
	znet.BaseRouter
}

func (r *HelloRouter) Handle(request ziface.IRequest) {
	message := znet.NewMessage(request.GetMessageID(), []byte("hello zinx"))
	err := request.GetConnection().SendBuffMsg(message)
	if err != nil {
		fmt.Println("send msg error")
		return
	}

}

//创建连接的时候执行
func DoConnectionBegin(conn ziface.IConnection) {
	fmt.Println("DoConnectionBegin is Called ... ")
	err := conn.SendMsg(znet.NewMessage(0, []byte("探测数据")))
	if err != nil {
		fmt.Println(err)
	}
}

//连接断开的时候执行
func DoConnectionLost(conn ziface.IConnection) {
	fmt.Println("DoConnectionLost is Called ... ")
}

func main() {
	server := znet.NewServer()
	helloRouter := HelloRouter{}
	pingRouter := PingRouter{}
	server.AddRouter(0, &helloRouter)
	server.AddRouter(1, &pingRouter)
	server.SetOnConnStart(DoConnectionBegin)
	server.SetOnConnStop(DoConnectionLost)
	server.Serve()
}
